package com.study.manage.dal;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

import com.study.manage.domain.Memo;

public interface MemoRepository extends PagingAndSortingRepository<Memo, Long> {

    @Query("select m from Memo m where evaluateId in (?1) and state=0 "
            + "and (DATEDIFF(createdAt, ?2) >= 0 or ?2 = '' or ?2 is null) "
            + "and (DATEDIFF(createdAt, ?3) <= 0 or ?3 = '' or ?3 is null) "
            + "and (context like ?4 or ?4 = '' or ?4 is null) ")
    Page<Memo> getMemoDatas(List<Long> evaluateIds, String timeFrom, String timeTo, String context,
            Pageable pageable);

    @Query(nativeQuery = true,
            value = "select * from sa_memo where evaluate_id in (?1) and state=0 ORDER BY created_at DESC LIMIT 0,4 ")
    List<Memo> getMemoDatas(List<Long> evaluateIds);

    @Query("select t from Memo t where t.evaluateId in (:evaluateIds) and t.state=0")
    Page<Memo> findByEvaluateIdIn(@Param("evaluateIds") List<Long> evaluateIds, Pageable pageable);

    @Modifying
    @Query("update Memo set state=1 where id=?1")
    void updateState(Long id);

    @Modifying
    @Query("update Memo set context=?2 where id=?1")
    void updateContext(Long id, String context);

    @Modifying
    @Query(nativeQuery = true,
            value = "insert into sa_memo(created_at,context,evaluate_id) values(NOW(), ?2 , ?1)")
    void insertMemo(Long id, String context);

}
